from app.libs.redprint import Redprint
from app.libs.redprint import Redprint
from app.models.book import Book
from flask import jsonify
from sqlalchemy import or_

from app.validators.forms import BookSearchForm

api = Redprint('book')


# 问题
# 1. 蓝图应该作为一个包级别的对象来使用
# 2. 路由 /v1/book 有点冗余

# 根据蓝图来定义属于自己的红图


@api.route('/search')
def search():
    # /search?q=python
    form = BookSearchForm().validate_for_api()
    q = '%' + form.q.data + '%'
    books = Book.query.filter(
        or_(Book.title.like(q), Book.publisher.like(q))).all()
    books = [book.hide('summary') for book in books]
    return jsonify(books)

    #  select * from  book where  title like '%python%'


@api.route('/<isbn>/detail')
def detail(isbn):
    book = Book.query.filter_by(isbn=isbn).first_or_404()
    return jsonify(book)
